package com.block.risk.service.type.item;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.block.risk.model.result.RiskJudgeResult;
import com.block.risk.service.IDefaultItemService;
import org.springframework.stereotype.Service;

@Service
public class YuJuItemService implements IDefaultItemService {
    @Override
    public RiskJudgeResult getControlResult(JSONObject resultDetial) {

        /**
         * 订单结清笔数8笔以上。
         * 订单比例90以上，
         * 近6个月逾期M0，
         * 近一个月贷款机构放款笔数1笔以上，
         * 成功扣款笔数大于失败笔数.
         */

        RiskJudgeResult riskJudgeResult = new RiskJudgeResult();
        riskJudgeResult.setPass(false);

        JSONObject currentReportDetail = resultDetial.getJSONObject("current_report_detail");
        JSONObject behaviorReportDetail = resultDetial.getJSONObject("behavior_report_detail");
        JSONObject applyReportDetail = resultDetial.getJSONObject("apply_report_detail");

        if (ObjectUtil.isEmpty(behaviorReportDetail)){
            riskJudgeResult.setResult("行为数据结果为空；【behavior_report_detail】");
            return riskJudgeResult;
        }

        // 订单结清笔数8笔以上
        // 贷款已结清订单数
        String numberSettle = behaviorReportDetail.getString("B22170052");
        if (Integer.valueOf(numberSettle) < 8){
            riskJudgeResult.setResult(StrUtil.format("订单结清笔数8笔以上不通过；【{}】", numberSettle));
            return riskJudgeResult;
        }

        // 订单比例90以上
        // 正常还款订单数占贷款总订单数比例
        String numberRate = behaviorReportDetail.getString("B22170034");
        numberRate = numberRate.replace("%", "");
        if (Integer.valueOf(numberRate) < 90){
            riskJudgeResult.setResult(StrUtil.format("订单比例90以上不通过；【{}】", numberRate));
            return riskJudgeResult;
        }

        // 近6个月逾期M0 = 0
        String numberSixM0 = behaviorReportDetail.getString("B22170025");
        if (Integer.valueOf(numberSixM0) > 0){
            riskJudgeResult.setResult(StrUtil.format("近6个月逾期M0不通过；【{}】", numberSixM0));
            return riskJudgeResult;
        }

        // 成功扣款笔数大于失败笔数.
        String numberSuccess = behaviorReportDetail.getString("B22170045");
        String numberFailed = behaviorReportDetail.getString("B22170035");
        if (Integer.valueOf(numberFailed) >= Integer.valueOf(numberSuccess)){
            riskJudgeResult.setResult(StrUtil.format("成功扣款笔数大于失败笔数不通过；成功扣款笔数【{}】失败笔数【{}】", numberSuccess, numberFailed ));
            return riskJudgeResult;
        }

        //B22170007 近1个月货款总金额
        String B22170016 = behaviorReportDetail.getString("B22170016");
        if (Integer.valueOf(B22170016) == 0){
            riskJudgeResult.setResult(StrUtil.format("近一个月贷款机构书；【{}】", B22170016));
            return riskJudgeResult;
        }

        riskJudgeResult.setPass(true);
        riskJudgeResult.setResult("全景分控通过");
        return riskJudgeResult;
    }
}
